package com.feihong.yw189.paidan.qiangdanservice;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.widget.Toast;

import com.amap.api.location.CoordinateConverter;
import com.amap.api.location.DPoint;

import java.math.BigDecimal;
import java.net.URISyntaxException;

import static java.lang.Math.atan2;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;

/**
 * Created by admin on 2018/2/4.
 */

public class LocationSDKTools {

    public static final int TYPE_BAIDU = 1;
    public static final int TYPE_GAODE = 2;
    public static final int TYPE_TENGXUN = 3;

    private Context mContext;
    private Intent intent;
    private LocationUtils mEnd;
    private int type = TYPE_GAODE;

    public LocationSDKTools(Context context) {
        this.mContext = context;
        intent = new Intent();
    }

    public void GOTO(int type, LocationUtils mEnd) {
        this.mEnd = mEnd;
        this.type = type;
        switch (type) {
            case TYPE_BAIDU:
                gotoBaidu();
                break;
            case TYPE_GAODE:
                gotoGaoDe();
                break;
            case TYPE_TENGXUN:
                gotoTengXun();
                break;
            default:
                Toast.makeText(mContext, "没有这样的地图", Toast.LENGTH_SHORT).show();
        }
    }

    public void gotoGaoDe() {
        //检测安装和唤起
        if (checkMapAppsIsExist(mContext, GAODE_PKG)) {
            //Toast.makeText(MainActivity.this,"高德地图已经安装",Toast.LENGTH_SHORT).show();
            //  BD09ToGCJ02(mStart, mEnd);
            try {
                DPoint point = new DPoint(mEnd.getLatitude(), mEnd.getLongitude());
                CoordinateConverter converter = new CoordinateConverter(mContext);
// CoordType.GPS 待转换坐标类型
                converter.from(CoordinateConverter.CoordType.GPS);
// sourceLatLng待转换坐标点 LatLng类型
                converter.coord(point);

// 执行转换操作
                DPoint desLatLng = converter.convert();
                Intent intentOther = new Intent("android.intent.action.VIEW",
                        Uri.parse("amapuri://route/plan/?sid=BGVIS1&did=BGVIS2&dlat=" + desLatLng.getLatitude() +
                                "&dlon=" + desLatLng.getLongitude() + "&dname=" + mEnd.getName() + "&dev=0&t=0")//跳转至路径规划
                        /*Uri.parse("androidamap://navi?sourceApplication=e游客&poiname=我的目的地&lat="
                                + mPosition.get(2) + "&lon=" +  mPosition.get(3) + "&dev=0&style=2")*/);//直接跳转至导航
                intentOther.addCategory("android.intent.category.DEFAULT");
                intentOther.setPackage("com.autonavi.minimap");
                intentOther.setAction("android.intent.action.VIEW");
                intentOther.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                mContext.startActivity(intentOther);
            } catch (Exception e) {

            }
            //   Toast.makeText(mContext, "高德地图", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(mContext, "高德地图未安装", Toast.LENGTH_SHORT).show();
        }
    }

    public double[] gaoDeToBaidu(double gd_lon, double gd_lat) {
        double[] bd_lat_lon = new double[2];
        double PI = 3.14159265358979324 * 3000.0 / 180.0;
        double x = gd_lon, y = gd_lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * PI);
        bd_lat_lon[0] = z * Math.cos(theta) + 0.0065;
        bd_lat_lon[1] = z * Math.sin(theta) + 0.006;
        return bd_lat_lon;
    }

    private void gotoBaidu() {
        //检测地图是否安装和唤起
        if (checkMapAppsIsExist(mContext, BAIDU_PKG)) {
            //Toast.makeText(mContext, "百度地图已经安装", Toast.LENGTH_SHORT).show();
            double[] locationDes = GPSUtil.gps84_To_bd09(mEnd.getLatitude(), mEnd.getLongitude());
            try {
                intent = Intent.getIntent("intent://map/direction?" +
                        //  "origin=latlng:" + mStart.getLatitude() + "," + mStart.getLongitude() + "&" +   //起点  此处不传值默认选择当前位置
                        "destination=latlng:" + locationDes[0] + "," + locationDes[1] + "|name:" + mEnd.getName() +        //终点
                        "&mode=drivingreferer=Autohome|GasStation#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }

            mContext.startActivity(intent);
            //     Toast.makeText(mContext, "百度地图", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(mContext, "百度地图未安装", Toast.LENGTH_SHORT).show();
        }

    }

    private void gotoTengXun() {
        if (checkMapAppsIsExist(mContext, TX_PKG)) {
            // Toast.makeText(MainActivity.this,"腾讯地图已经安装",Toast.LENGTH_SHORT).show();
            // BD09ToGCJ02(mStart, mEnd);
            //将功能Scheme以URI的方式传入data
            Intent intent = null;
            try {
                DPoint point = new DPoint(mEnd.getLatitude(), mEnd.getLongitude());
                CoordinateConverter converter = new CoordinateConverter(mContext);
// CoordType.GPS 待转换坐标类型
                converter.from(CoordinateConverter.CoordType.GPS);
// sourceLatLng待转换坐标点 LatLng类型
                converter.coord(point);

// 执行转换操作
                DPoint desLatLng = converter.convert();
                Intent intentOther = new Intent("android.intent.action.VIEW",
                        Uri.parse("amapuri://route/plan/?sid=BGVIS1&sname=" + "" + "&did=BGVIS2&dlat=" + desLatLng.getLatitude() +
                                "&dlon=" + desLatLng.getLongitude() + "&dname=" + mEnd.getName() + "&dev=0&t=0"));//跳转至路径规划
                // intentOther.setPackage(TX_PKG);
                mContext.startActivity(intentOther);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //   Toast.makeText(mContext, "腾讯地图", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(mContext, "腾讯地图未安装", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 坐标转换
     *
     * @param mStart
     * @param mEnd
     */
    public void BD09ToGCJ02(LocationUtils mStart, LocationUtils mEnd) {
        DPoint newStart = convertBaiduToGPS(new DPoint(mStart.getLatitude(), mStart.getLongitude()));
        DPoint newEnd = convertBaiduToGPS(new DPoint(mEnd.getLatitude(), mEnd.getLongitude()));
        mStart.setLatitude(newStart.getLatitude());
        mStart.setLongitude(newStart.getLongitude());

        mEnd.setLatitude(newEnd.getLatitude());
        mEnd.setLongitude(newEnd.getLongitude());

    }

    /**
     * 检测地图应用是否安装
     *
     * @param context
     * @param packagename
     * @return
     */
    public boolean checkMapAppsIsExist(Context context, String packagename) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packagename, 0);
        } catch (Exception e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if (packageInfo == null) {
            return false;
        } else {
            return true;
        }
    }

    //高德转百度
    void bd_encrypt(double gg_lat, double gg_lon, double bd_lat, double bd_lon) {
        double x = gg_lon, y = gg_lat;
        double z = sqrt(x * x + y * y) + 0.00002 * sin(y * Math.PI);
        double theta = atan2(y, x) + 0.000003 * cos(x * Math.PI);
        bd_lon = z * cos(theta) + 0.0065;
        bd_lat = z * sin(theta) + 0.006;
    }

    /**
     * 将百度地图坐标转换成GPS坐标
     *
     * @param sourceLatLng
     * @return
     */
    public DPoint convertBaiduToGPS(DPoint sourceLatLng) {
        // 将GPS设备采集的原始GPS坐标转换成百度坐标
        CoordinateConverter converter = new CoordinateConverter(mContext);
        converter.from(CoordinateConverter.CoordType.GPS);
        // sourceLatLng待转换坐标

        DPoint desLatLng = null;
        try {
            converter.coord(sourceLatLng);
            desLatLng = converter.convert();
        } catch (Exception e) {
            e.printStackTrace();
        }
        double latitude = 2 * sourceLatLng.getLatitude() - desLatLng.getLatitude();
        double longitude = 2 * sourceLatLng.getLongitude() - desLatLng.getLongitude();
        BigDecimal bdLatitude = new BigDecimal(latitude);
        bdLatitude = bdLatitude.setScale(6, BigDecimal.ROUND_HALF_UP);
        BigDecimal bdLongitude = new BigDecimal(longitude);
        bdLongitude = bdLongitude.setScale(6, BigDecimal.ROUND_HALF_UP);
        return new DPoint(bdLatitude.doubleValue(), bdLongitude.doubleValue());
    }


    //头部 添加相应地区
    private final static String BAIDU_HEAD = "baidumap://map/direction?region=0";
    //起点的经纬度
    private final static String BAIDU_ORIGIN = "&origin=";
    //终点的经纬度
    private final static String BAIDU_DESTINATION = "&destination=";
    //路线规划方式
    private final static String BAIDU_MODE = "&mode=walking";
    //百度地图的包名
    private final static String BAIDU_PKG = "com.baidu.BaiduMap";


    //头部 后面的sourceApplicaiton填自己APP的名字
    private final static String GAODE_HEAD = "androidamap://route?sourceApplication=营维189";
    //起点经度
    private final static String GAODE_SLON = "&slon=";
    //起点纬度
    private final static String GAODE_SLAT = "&slat=";
    //起点名字
    private final static String GAODE_SNAME = "&sname=";
    //终点经度
    private final static String GAODE_DLON = "&dlon=";
    //终点纬度
    private final static String GAODE_DLAT = "&dlat=";
    //终点名字
    private final static String GAODE_DNAME = "&dname=";
    // dev 起终点是否偏移(0:lat 和 lon 是已经加密后的,不需要国测加密; 1:需要国测加密)
    // t = 1(公交) =2（驾车） =4(步行)
    private final static String GAODE_MODE = "&dev=0&t=2";
    //高德地图包名
    private final static String GAODE_PKG = "com.autonavi.minimap";


    //头部 type出行方式
    private final static String TX_HEAD = "qqmap://map/routeplan?type=walk";
    //起点名称
    private final static String TX_FROM = "&from=";
    //起点的经纬度
    private final static String TX_FROMCOORD = "&fromcoord=";
    //终点名称
    private final static String TX_TO = "&to=";
    //终点的经纬度
    private final static String TX_TOCOORD = "&tocoord=";
    /**
     * 本参数取决于type参数的取值
     * 公交：type=bus，policy有以下取值
     * 0：较快捷
     * 1：少换乘
     * 2：少步行
     * 3：不坐地铁
     * 驾车：type=drive，policy有以下取值
     * 0：较快捷
     * 1：无高速
     * 2：距离
     * policy的取值缺省为0
     */
    private final static String TX_END = "&policy=1&referer=myapp";
    //腾讯地图包名
    private final static String TX_PKG = "com.tencent.map";


}
